<?php

use sef\controller;
use sef\model;
use weixin\mp;

class kf_controller extends base_controller {
    //protected $app_type = 'common';
    //protected $auth_map = array('read' => 'read_talk,send_text,send_image,send_file,nofify,qrcode,map,image,voice,baoan,jubao,todo,finish,get_talk_content,let_me_do,mark_finish_form_todo,mark_finish_from_index,bind','admin'=>'admin,hb_list,send_hb');

    public function index() {
        $where[] = array('user_id', 'eq', get_user_id());
        $where[] = array('is_finish', 'eq', 0);

        $model = model('kf_talk');
        $model -> select('kf_talk.from_user_name,kf_talk.id,kf_vistor.nickname,kf_vistor.headimgurl');
        $model -> left('kf_vistor', 'kf_vistor.openid=kf_talk.from_user_name');
        $talk_list = $model -> where($where) -> get_list();
        $this -> assign('talk_list', $talk_list);

        $where = null;
        $favorite_list = model('kf_favorite') -> get_list();
        $this -> assign('favorite_list', $favorite_list);

        $this -> display();
    }

    public function baoan() {
        $where[] = array('is_accept', 'eq', 0);
        $where[] = array('type', 'eq', 1);

        $model = model('kf_talk');
        $model -> select('kf_talk.from_user_name,kf_talk.id,kf_vistor.nickname,kf_vistor.headimgurl');
        $model -> left('kf_vistor', 'kf_vistor.openid=kf_talk.from_user_name');

        $talk_list = $model -> where($where) -> get_list();
        $this -> assign('talk_list', $talk_list);

        $where = null;
        $favorite_list = model('kf_favorite') -> get_list();
        $this -> assign('favorite_list', $favorite_list);

        $this -> display();
    }

    public function jubao() {
        $where[] = array('is_accept', 'eq', 0);
        $where[] = array('type', 'eq', 2);

        $model = model('kf_talk');
        $model -> select('kf_talk.from_user_name,kf_talk.id,kf_vistor.nickname,kf_vistor.headimgurl');
        $model -> left('kf_vistor', 'kf_vistor.openid=kf_talk.from_user_name');

        $talk_list = $model -> where($where) -> get_list();
        $this -> assign('talk_list', $talk_list);

        $where = null;
        $favorite_list = model('kf_favorite') -> get_list();
        $this -> assign('favorite_list', $favorite_list);

        $this -> display();
    }

    public function todo() {
        $where[] = array('is_accept', 'eq', 0);
        $where[] = array('type', 'eq', 0);

        $model = model('kf_talk');
        $model -> select('kf_talk.from_user_name,kf_talk.id,kf_vistor.nickname,kf_vistor.headimgurl');
        $model -> left('kf_vistor', 'kf_vistor.openid=kf_talk.from_user_name');

        $talk_list = $model -> where($where) -> get_list();
        $this -> assign('talk_list', $talk_list);

        $where = null;
        $favorite_list = model('kf_favorite') -> get_list();
        $this -> assign('favorite_list', $favorite_list);

        $this -> display();
    }

    public function finish() {
        $is_adv_search = false;
        if (request('keyword')) {
            $where_log[] = array('content', 'like', request('keyword'));
            $is_adv_search = true;
        }
        if (request('be_create_time') && request('en_create_time')) {
            $where_log[] = array('create_time', 'egt', date_to_int(request('be_create_time')));
            $where_log[] = array('create_time', 'elt', date_to_int(request('en_create_time')) + 86400);
            $is_adv_search = true;
        }
        if (request('li_content')) {
            $where_log[] = array('content', 'like', request('li_content'));
            $is_adv_search = true;
        }
        if ($is_adv_search) {
            $talk_id = model('kf_talk_log') -> where($where_log) -> get_field('talk_id', true);
            if (!empty($talk_id)) {
                $where[] = array('kf_talk.id', 'in', $talk_id);
            } else {
                $where[] = array('string', '1=2');
            }

        }

        $where[] = array('user_id', 'eq', get_user_id());
        $where[] = array('is_finish', 'eq', 1);

        $model = model('kf_talk');
        $model -> select('kf_talk.id,kf_talk.from_user_name,kf_vistor.nickname,kf_vistor.headimgurl');
        $model -> left('kf_vistor', 'kf_vistor.openid=kf_talk.from_user_name');
        if (!empty($model)) {
            $talk_list = $this -> _list($model, $where);
        }
        $this -> assign('talk_list', $talk_list);

        $where = null;
        $favorite_list = model('kf_favorite') -> get_list();
        $this -> assign('favorite_list', $favorite_list);

        $this -> display();
    }

    public function admin() {

        $is_adv_search = false;
        if (request('keyword')) {
            $where_log[] = array('content', 'like', request('keyword'));
            $is_adv_search = true;
        }
        if (request('be_create_time') && request('en_create_time')) {
            $where_log[] = array('create_time', 'egt', date_to_int(request('be_create_time')));
            $where_log[] = array('create_time', 'elt', date_to_int(request('en_create_time')) + 86400);
            $is_adv_search = true;
        }
        if (request('li_content')) {
            $where_log[] = array('content', 'like', request('li_content'));
            $is_adv_search = true;
        }
        if ($is_adv_search) {
            $talk_id = model('kf_talk_log') -> where($where_log) -> get_field('talk_id', true);
            if (!empty($talk_id)) {
                $where[] = array('kf_talk.id', 'in', $talk_id);
            } else {
                $where[] = array('string', '1=2');
            }
        }

        if (request('type')) {
            $type = request('type');
            $where[] = array('type', 'eq', $type);
        } elseif (request('type') == '') {
            $type = 1;
            $where[] = array('type', 'eq', $type);
        } else {
            $type = request('type');
            $where[] = array('type', 'eq', $type);
        }

        $this -> assign('type', $type);
        // $where[] = array('user_id', 'eq', get_user_id());
        $where[] = array('is_finish', 'eq', 1);

        $model = model('kf_talk');
        $model -> select('kf_talk.id,kf_talk.from_user_name,kf_vistor.nickname,kf_vistor.headimgurl');
        $model -> left('kf_vistor', 'kf_vistor.openid=kf_talk.from_user_name');
        if (!empty($model)) {
            $talk_list = $this -> _list($model, $where);
        }
        $this -> assign('talk_list', $talk_list);

        $where = null;
        $favorite_list = model('kf_favorite') -> get_list();
        $this -> assign('favorite_list', $favorite_list);

        $this -> display();
    }

    public function let_me_do($talk_id) {
        $data['id'] = $talk_id;
        $data['user_id'] = get_user_id();
        $data['user_name'] = get_user_name();
        $data['is_accept'] = 1;
        $talk_id = model('kf_talk') -> save($data);

        $return['status'] = 1;
        $return['info'] = '请在【处理中】回复及处理';

        ajax_return($return);
    }

    public function mark_finish_from_todo($talk_id) {
        $data['id'] = $talk_id;
        $data['user_id'] = get_user_id();
        $data['user_name'] = get_user_name();
        $data['is_finish'] = 1;
        $data['is_accept'] = 1;
        $talk_id = model('kf_talk') -> save($data);

        $return['status'] = 1;
        $return['info'] = '已标记为【已完成】';

        $content = '当前会话已经结束，如果您有新的问题，请再次点击底部对应菜单';
        $this -> send_text($talk_id, $content, true);

        ajax_return($return);
    }

    public function mark_finish_from_index($id) {
        $where[] = array('id', 'eq', $id);
        $data['is_finish'] = 1;
        model('kf_talk') -> where($where) -> save($data);

        $return['status'] = 1;
        $return['info'] = '已标记为【已完成】';

        $content = '当前会话已经结束，如果您有新的问题，请再次点击底部对应菜单';
        $this -> send_text($id, $content, true);

        ajax_return($return);
    }

    public function bind() {
        import('socket_client');
        $socket_client = new socket_client();
        $msg['type'] = 'bind_user';
        $msg['client_id'] = request('client_id');
        $msg['user_id'] = get_user_id();

        $socket_client -> send($msg);
    }

    public function get_talk_content($id, $is_read = false) {
        $where[] = array('talk_id', 'eq', $id);
        if ($is_read) {
            $data['is_read'] = 1;
            model('kf_talk_log') -> where($where) -> save($data);
        }
        $model = model('kf_talk_log');
        $model -> select('kf_talk_log.user_name,kf_talk_log.from_user_name,kf_talk_log.action_type,kf_talk_log.msg_type,kf_talk_log.create_time,kf_talk_log.content,kf_vistor.nickname,kf_vistor.headimgurl,user.emp_no,kf_talk_log.location,kf_talk_log.pic_url,kf_talk_log.label,kf_talk_log.media_id,kf_talk_log.thumb_media_id');
        $model -> left('kf_vistor', 'kf_vistor.openid=kf_talk_log.from_user_name');
        $model -> left('user', 'user.id=kf_talk_log.user_id');
        $list = $model -> where($where) -> order('create_time') -> get_list();
        ajax_return($list);
    }

    public function get_talk_todo($from_user_name) {
        $where[] = array('is_accept', 'eq', 0);
        $where[] = array('from_user_name', 'eq', $from_user_name);
        $model = model('kf_talk_log');
        $model -> select('kf_vistor.nickname,kf_talk_log.from_user_name,kf_talk_log.action_type,kf_talk_log.msg_type,kf_talk_log.create_time,kf_talk_log.content,kf_talk_log.location,kf_talk_log.pic_url,kf_talk_log.label,kf_talk_log.media_id,kf_talk_log.thumb_media_id');
        $model -> left('kf_vistor', 'kf_vistor.openid=kf_talk_log.from_user_name');
        $list = $model -> where($where) -> get_list();

        ajax_return($list);
    }

    public function get_vistor_info($openid) {
        $where[] = array('openid', 'eq', $openid);
        $data = model('kf_vistor') -> where($where) -> find();
        ajax_return($data);
    }

    public function get_new_msg_count() {
        $where[] = array('is_read', 'eq', 0);
        $list = model('kf_talk_log') -> where($where) -> get_field('talk_id', true);
        ajax_return(array_count_values($list));
    }

    public function get_new_todo_count() {
        $where[] = array('action_type', 'eq', 'receive');
        $model = model('kf_talk_log');
        $model -> left('kf_talk', 'kf_talk.id=kf_talk_log.id');
        $list = $model -> where($where) -> get_field('from_user_name', true);
        if ($list !== false) {
            ajax_return(array_count_values($list));
        }
    }

    public function map($latlng) {
        $this -> assign('latlng', $latlng);
        $this -> display();
    }

    public function image($url) {
        echo file_get_contents($url);
    }

    public function voice($media_id) {
        $media_path = 'uploads/mp/voice/' . $media_id . '.amr';
        $base64 = base64_encode(file_get_contents($media_path));
        $this -> assign('base64', $base64);
        $this -> display();
    }

    public function video($media_id) {
        $media_path = 'uploads/mp/video/' . $media_id . '.mp4';
        $this -> assign('media_path', $media_path);
        $this -> display();
    }

    public function hb_list() {
        $model = model('kf_hb');
        $where = array();
        if (!empty($model)) {
            $hb_list = $this -> _list($model, $where);
        }
        $this -> display();
    }

    public function send_hb() {
        if (IS_POST) {

            $talk_id = request('talk_id');
            $where_hb[] = array('talk_id', 'eq', $talk_id);
            $hb_count = model('kf_hb') -> where($where_hb) -> count();

            if ($hb_count > 0) {
                $return['info'] = '红包只能发送一次';
                $return['status'] = 0;
                ajax_return($return);
            }

            $data['talk_id'] = $talk_id;
            $data['name'] = request('name');
            $data['send_name'] = request('send_name');
            $data['amount'] = request('amount');
            $data['wishing'] = request('wishing');
            $data['send_name'] = request('send_name');
            $data['remark'] = request('remark');
            $data['act_name'] = request('act_name');
            $data['user_id'] = get_user_id();
            $data['user_name'] = get_user_name();

            model('kf_hb') -> add($data);

            $info['send_name'] = request('send_name');
            $info['amount'] = request('amount');
            $info['wishing'] = request('wishing');
            $info['name'] = request('name');
            $info['send_name'] = request('send_name');
            $info['remark'] = request('remark');
            $info['act_name'] = request('act_name');
            $info['trade_no'] = $talk_id;

            $talk = model('kf_talk') -> find($talk_id);
            $info['openid'] = $talk['from_user_name'];

            import('weixin/pay/pay');

            $config = array();
            $config['wxappid'] = 'wxba2ecd3c518153b9';
            $config['mch_id'] = '1486794202';
            $config['api_cert'] = FRAMEWORK_PATH . 'ext/weixin/pay/cert/apiclient_cert.pem';
            $config['api_key'] = FRAMEWORK_PATH . 'ext/weixin/pay/cert/apiclient_key.pem';
            $config['pay_apikey'] = 'TFfJzsBo5yKBwi6WmVSCa2cycu0tLhja';

            $redpack = new WxRedpack($config);

            $ret = $redpack -> sendredpack($info);
            if (isset($ret['return_code']) && $ret['return_code'] = 'SUCCESS') {
                $return['info'] = '红包发送成功';
                $return['status'] = 1;
            } else {
                $return['info'] = '红包发送失败<br>' . $ret['msg'];
                $return['status'] = 0;
            }
            ajax_return($return);
        } else {
            $this -> display();
        }
    }

    public function read_talk($id) {
        $this -> assign('talk_id', $id);
        $this -> display();
    }

    public function send_text($id, $content, $debug = false) {

        $where[] = array('id', 'eq', $id);
        $open_id = model('kf_talk') -> where($where) -> get_field('from_user_name');

        $data['talk_id'] = $id;
        $data['user_id'] = get_user_id();
        $data['user_name'] = get_user_name();
        $data['msg_type'] = 'text';
        $data['to_user_name'] = $open_id;
        $data['content'] = $content;
        $data['action_type'] = 'send';
        $data['create_time'] = time();

        $id = model('kf_talk_log') -> add($data);

        import('weixin/mp/helper');
        import('weixin/mp/msg_sender');

        $msg_sender = new mp\msg_sender();

        //发送文字
        $msg['touser'] = $open_id;
        $msg['msgtype'] = 'text';
        $msg['text']['content'] = $content;
        $ret = json_decode($msg_sender -> send($msg), true);
        if($debug){
            return;
        }
        if ($ret['errcode'] == 0) {
            $return['status'] = 1;
            ajax_return($ret);
        } else {
            $return['status'] = 0;
            ajax_return($ret);
        }
    }

    public function send_image($id) {
        //上传文件
        $code = 0;
        $upload_img_path = $msg = "";
        // 没找到文件
        if (empty($_FILES)) {
            $code = 400;
            $msg = "没找到文件";
        } else {
            $file_name = $_FILES['file']['name'];
            // 获得后缀名
            $extension_name = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
            // 计算上传路径
            $upload_img_path = 'uploads/mp/image/' . bin2hex(pack('N', time()) . pack('n', rand(1, 65535))) . '.' . $extension_name;
            // 为了安全，禁止这些文件上传
            if ($extension_name === 'php' || $extension_name === 'asp' || $extension_name === 'jsp') {
                $code = 401;
                $msg = "上传文件非法";
            } else {
                if (!move_uploaded_file($_FILES['file']['tmp_name'], $upload_img_path)) {
                    $code = 500;
                    $msg = "保存文件失败";
                }
            }
            // 检查是否是图片
            if ($code == 0 && !getimagesize($upload_img_path)) {
                $code = 502;
                $msg = "上传的文件不是图片";
                unlink($upload_img_path);
            }
        }

        //返回JSON数据
        $src = $upload_img_path;
        $return['code'] = $code;
        $return['msg'] = $msg;
        $return['data']['src'] = $src;
        ob_start();
        echo(json_encode($return));
        ob_flush();
        flush();

        //插入到数据库

        $where[] = array('id', 'eq', $id);
        $open_id = model('kf_talk') -> where($where) -> get_field('from_user_name');

        $data['talk_id'] = $id;
        $data['user_id'] = get_user_id();
        $data['user_name'] = get_user_name();
        $data['msg_type'] = 'image';
        $data['to_user_name'] = $open_id;
        $data['pic_url'] = $upload_img_path;
        $data['action_type'] = 'send';
        $data['create_time'] = time();

        $id = model('kf_talk_log') -> add($data);

        //上传附件到微信
        import('weixin/mp/helper');
        import('weixin/mp/msg_sender');

        //echo $upload_img_path;

        $msg_sender = new mp\msg_sender();
        $ret = $msg_sender -> upload_media($upload_img_path, 'image');

        //print_r($ret);
        //发送文字
        $msg['touser'] = $open_id;
        $msg['msgtype'] = 'image';
        $msg['image']['media_id'] = $ret['media_id'];
        $ret = json_decode($msg_sender -> send($msg), true);
    }

    public function send_file($id) {
        //上传文件
        $code = 0;
        $upload_file_path = $msg = "";
        // 没找到文件
        if (empty($_FILES)) {
            $code = 400;
            $msg = "没找到文件";
        } else {
            $file_name = $_FILES['file']['name'];
            // 获得后缀名
            $extension_name = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
            // 计算上传路径
            $upload_file_path = 'uploads/mp/file/' . bin2hex(pack('N', time()) . pack('n', rand(1, 65535))) . '.' . $extension_name;
            // 为了安全，禁止这些文件上传
            if ($extension_name === 'php' || $extension_name === 'asp' || $extension_name === 'jsp') {
                $code = 401;
                $msg = "上传文件非法";
            } else {
                if (!move_uploaded_file($_FILES['file']['tmp_name'], $upload_file_path)) {
                    $code = 500;
                    $msg = "保存文件失败";
                }
            }
        }

        //返回JSON数据
        $src = $upload_file_path;
        $return['code'] = $code;
        $return['msg'] = $msg;
        $return['data']['src'] = $src;
        ob_start();
        echo(json_encode($return));
        ob_flush();
        flush();

        //插入到数据库

        $where[] = array('id', 'eq', $id);
        $open_id = model('kf_talk') -> where($where) -> get_field('from_user_name');

        $data['talk_id'] = $id;
        $data['user_id'] = get_user_id();
        $data['user_name'] = get_user_name();
        $data['msg_type'] = 'image';
        $data['to_user_name'] = $open_id;
        $data['pic_url'] = $upload_file_path;
        $data['action_type'] = 'send';
        $data['create_time'] = time();

        $id = model('kf_talk_log') -> add($data);

        //上传附件到微信
        import('weixin/mp/helper');
        import('weixin/mp/msg_sender');

        //echo $upload_img_path;

        $msg_sender = new mp\msg_sender();
        $ret = $msg_sender -> upload_media($upload_file_path, 'image');

        //print_r($ret);
        //发送文字
        $msg['touser'] = $open_id;
        $msg['msgtype'] = 'image';
        $msg['image']['media_id'] = $ret['media_id'];
        $ret = json_decode($msg_sender -> send($msg), true);
    }

    private function add_talk_log($data) {
        $model = model('kf_talk_log');
        $new['action_type'] = 'receive';
        if (isset($data['ToUserName'])) {
            $new['to_user_name'] = $data['ToUserName'];
        }
        if (isset($data['FromUserName'])) {
            $new['from_user_name'] = $data['FromUserName'];
        }
        if (isset($data['CreateTime'])) {
            $new['create_time'] = $data['CreateTime'];
        }
        if (isset($data['MsgType'])) {
            $new['msg_type'] = $data['MsgType'];
        }
        if (isset($data['Content'])) {
            $new['content'] = $data['Content'];
        }
        if (isset($data['MsgId'])) {
            $new['msg_id'] = $data['MsgId'];
        }
        if (isset($data['PicUrl'])) {
            $new['pic_url'] = $data['PicUrl'];
        }
        if (isset($data['MediaId'])) {
            $new['media_id'] = $data['MediaId'];
        }
        if (isset($data['Format'])) {
            $new['format'] = $data['Format'];
        }
        if (isset($data['Recognition'])) {
            $new['recognition'] = $data['Recognition'];
        }
        if (isset($data['ThumbMediaId'])) {
            $new['thumb_media_id'] = $data['ThumbMediaId'];
        }
        if (isset($data['Location_X'])) {
            $location['x'] = $data['Location_X'];
        }
        if (isset($data['Location_Y'])) {
            $location['y'] = $data['Location_Y'];
        }
        if (isset($data['Scale'])) {
            $location['scale'] = $data['Scale'];
        }
        if (isset($location)) {
            $new['location'] = json_encode($location);
        }
        if (isset($data['Label'])) {
            $new['label'] = $data['Label'];
        }
        $model -> add($new);
    }

    private function add_vistor($user_info) {

        $model = model('kf_vistor');
        $where[] = array('openid', 'eq', $user_info["openid"]);
        $ret = $model -> where($where) -> find();
        if ($ret == false) {
            $data['subscribe'] = $user_info['subscribe'];
            $data['openid'] = $user_info['openid'];
            $data['nickname'] = $user_info['nickname'];
            $data['sex'] = $user_info['sex'];
            $data['city'] = $user_info['city'];
            $data['country'] = $user_info['country'];
            $data['province'] = $user_info['province'];
            $data['language'] = $user_info['language'];
            $data['headimgurl'] = $user_info['headimgurl'];
            $data['subscribe_time'] = $user_info['subscribe_time'];
            $model -> add($data);
        }
    }

    public function create_menu() {

        $menu1['type'] = 'click';
        $menu1['name'] = '在线报案';
        $menu1['key'] = 'BAOAN';

        $menu2['type'] = 'click';
        $menu2['name'] = '线索举报';
        $menu2['key'] = 'JUBAO';

        $menu3['type'] = 'view';
        $menu3['name'] = '新闻';
        $menu3['url'] = 'http://kf.xiaoweioa.com/index.php?app=public&method=news_index';

        $menu['button'][] = $menu1;
        $menu['button'][] = $menu2;
        $menu['button'][] = $menu3;

        echo json_encode($menu, JSON_UNESCAPED_UNICODE);

        //上传附件到微信
        import('weixin/mp/helper');
        import('weixin/mp/msg_sender');
        $msg_sender = new mp\msg_sender();

        $ret = json_decode($msg_sender -> create_menu($menu), true);
        print_r($ret);
        die ;
        ajax_return($ret);
        if ($ret['errcode'] == 0) {
            $return['status'] = 1;
            ajax_return($return);
        } else {
            $return['status'] = 0;
            ajax_return($return);
        }
    }

    public function notify($type) {

        import('weixin/mp/helper');
        import('weixin/mp/msg_sender');

        $msg_sender = new mp\msg_sender();
        //print_r($ret);
        //发送文字
        $data['expire_seconds'] = 604800;
        $data['action_name'] = 'QR_STR_SCENE';
        $data['action_info']['scene']['scene_str'] = 'type' . $type;

        //echo(json_encode($data));

        $ret = json_decode($msg_sender -> create_qrcode($data), true);

        $this -> assign('qrcode_url', $ret['url']);
        $this -> display();
    }

    public function qrcode($str) {
        vendor();
        $qrCode = new Endroid\QrCode\QrCode();
        //$str = "http://car.smeoa.com/index.php?app=car&qrcode=" . $qrcode;
        //echo $str;
        $qrCode -> setText($str);
        $qrCode -> setSize(300);
        $qrCode -> setPadding(10);
        $qrCode -> render();
        die ;
    }

}
